const collectModel = appRequire('models/collect');

// 导出对象，供其它模块调用
module.exports = {
    collect,
    list,
};

//收藏列表
async function list(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;

    let result2 = await collectModel.collect.findAndCountAll({
        where: {
            userId: postData.uid,
        },
        include: ["artPPT"],
        order: [['createdAt', 'DESC']],
        limit: postData.pageSize,
        offset: postData.pageSize * (postData.pageNum - 1)
    })

    result2 = Common.clone(result2)
    result2.rows = await Common.transfromDataList(result2.rows)

    returnData.maxCount = result2.count
    returnData.maxPage = Math.ceil(result2.count / postData.pageSize)
    returnData.data = result2.rows

    request.json(returnData)
}

//收藏
async function collect(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;

    let params = {
        userId: postData.uid,
    }
    if (postData.artpptId) params.artpptId = postData.artpptId
    if (postData.artPaintingId) params.artPaintingId = postData.artPaintingId

    let result2 = await collectModel.collect.findOne({
        where: params
    })
    if (result2) {
        let result3 = await collectModel.collect.destroy({
            where: {
                objectId: result2.objectId,
                userId: postData.uid,
            }
        })
        returnData.data = result3
        returnData.msg = "取消收藏成功"
    } else {
        let params = {
            objectId: sid.uuid(),
            userId: postData.uid,
        }
        if (postData.artpptId) params.artpptId = postData.artpptId
        if (postData.artPaintingId) params.artPaintingId = postData.artPaintingId
        let result3 = await collectModel.collect.create(params)
        returnData.data = result3
        returnData.msg = "收藏成功"
    }

    request.json(returnData)
}
